package com.xiaoma.mvi

import android.os.Bundle
import android.transition.TransitionInflater
import android.util.Log
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.*
import com.xiaoma.mvi.databinding.FragmentRepeatOnLifecycleBinding
import com.xiaoma.mvi.func.BindingFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class RepeatOnLifecycleFragment : BindingFragment<FragmentRepeatOnLifecycleBinding>() {
    companion object {
        private val TAG = "${RepeatOnLifecycleFragment::class.simpleName}Tag"
    }

    private val vm by viewModels<Vm>()

    override fun onResume() {
        super.onResume()
        enterTransition = TransitionInflater.from(requireContext())
            .inflateTransition(R.transition.fragment_exit)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                Log.d(TAG, "view onResume")
            }

            override fun onPause(owner: LifecycleOwner) {
                Log.d(TAG, "view onPause")
            }
        })

        viewLifecycleOwner.lifecycleScope.launch {
            vm.textState.collect { uuid ->
                Log.w(TAG, "on new state: $uuid")
                binding.tvText.text = uuid
            }
        }
    }

    class Vm : ViewModel() {

        private val _textState = MutableStateFlow("")
        val textState = _textState.asStateFlow()

        init {
            Log.d(TAG, "viewModel init")

            viewModelScope.launch {
                while (true) {
                    delay(2000)
                    withContext(Dispatchers.Default) {
                        Log.e(TAG, "change state")
                        _textState.update { UUID.randomUUID().toString() }
                    }
                }
            }
        }

        override fun onCleared() {
            Log.d(TAG, "viewModel onCleared")
        }

    }

}